package com.fengxing.ams.pub.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.fengxing.ams.pub.AMSException;
import com.fengxing.ams.pub.constants.ReltCode;
import com.fengxing.ams.pub.email.EmailParam;
import com.fengxing.ams.pub.manager.SpringContextManager;
import com.fengxing.ams.pub.manager.intf.IConfigManager;

/**
 * 
 * @author Lee
 * @date 2014-11-18
 * 
 */
public class EmailUtil {

	public static Boolean sendEmail(String emailAddress, Object... message) {
		IConfigManager configManager = SpringContextManager.getBean(IConfigManager.class);
		String path = configManager.getProperty(EmailParam.SEND_EMAIL_FILEPATH.getSysPropName(), EmailParam.SEND_EMAIL_FILEPATH.getDefaultValue());
		Resource rs = new ClassPathResource(path);
//		try {
//			rs.getFile();
//		} catch (FileNotFoundException e) {
//			rs = new ClassPathResource(path);
//		} catch (IOException e1) {
//			rs = new ClassPathResource(path);
//		}
		try {
			rs.getFile();
		} catch (FileNotFoundException e) {
			rs = new FileSystemResource(path);
		} catch (IOException e1) {
			rs = new FileSystemResource(path);
		}
		List<Properties> plist = new ArrayList<Properties>();
		Properties current = null;
		try {
			BufferedReader reader = new BufferedReader(new FileReader(rs.getFile()));
			String line = "";
			while (!StringUtils.isBlank((line = reader.readLine()))) {
				String[] email = line.split(" ");
				if (email == null || email.length < 4) {
					continue;
				}
				Properties p = new Properties();
				p.setProperty(EmailParam.SEND_EMAIL_USER.getSysPropName(), email[0]);
				p.setProperty(EmailParam.SEND_EMAIL_PASSWORD.getSysPropName(), email[1]);
				p.setProperty(EmailParam.SEND_EMAIL_HOST.getSysPropName(), email[2]);
				p.setProperty(EmailParam.SEND_EMAIL_PORT.getSysPropName(), email[3]);
				plist.add(p);
			}
		} catch (FileNotFoundException e1) {
			throw new AMSException(ReltCode.SERVER_INTERNAL_ERROR, "请联系管理员");
		} catch (IOException e1) {
			throw new AMSException(ReltCode.SERVER_INTERNAL_ERROR, "请联系管理员");
		}
		Random random = new Random();
		if (plist.size() < 1) {
			throw new AMSException(ReltCode.SERVER_INTERNAL_ERROR, "请联系管理员");
		}
		if (plist.size() == 1) {
			current = plist.iterator().next();
		} else {
			current = plist.get(random.nextInt(plist.size() - 1));
		}
		if (current == null) {
			throw new AMSException(ReltCode.SERVER_INTERNAL_ERROR, "请联系管理员");
		}

		// Properties p = new Properties();
		current.put(EmailParam.SEND_EMAIL_TIMEOUT.getSysPropName(), configManager.getProperty(EmailParam.SEND_EMAIL_TIMEOUT.getSysPropName(), EmailParam.SEND_EMAIL_TIMEOUT.getDefaultValue()));
		current.put(EmailParam.SEND_EMAIL_AUTH.getSysPropName(), configManager.getProperty(EmailParam.SEND_EMAIL_AUTH.getSysPropName(), EmailParam.SEND_EMAIL_AUTH.getDefaultValue()));
		current.put(EmailParam.SEND_EMAIL_MESSAGE.getSysPropName(), configManager.getProperty(EmailParam.SEND_EMAIL_MESSAGE.getSysPropName(), EmailParam.SEND_EMAIL_MESSAGE.getDefaultValue()));
		current.put(EmailParam.SEND_EMAIL_SUBJECT.getSysPropName(), configManager.getProperty(EmailParam.SEND_EMAIL_SUBJECT.getSysPropName(), EmailParam.SEND_EMAIL_SUBJECT.getDefaultValue()));
		// StringBuffer sf = new StringBuffer();
		// if(StringUtils.isBlank(p.getProperty(EmailParam.SEND_EMAIL_HOST.getSysPropName())) ) {
		// sf.append("请设置mail.smtp.host的值.\n");
		// }
		// if(StringUtils.isBlank(p.getProperty(EmailParam.SEND_EMAIL_USER.getSysPropName())) ) {
		// sf.append("请设置mail.smtp.username的值.\n");
		// }
		// if(StringUtils.isBlank(p.getProperty(EmailParam.SEND_EMAIL_PASSWORD.getSysPropName())) ) {
		// sf.append("请设置mail.smtp.password的值.\n");
		// }
		// if(StringUtils.isNotBlank(sf.toString())) {
		// throw new AMSException(ReltCode.SERVER_INTERNAL_ERROR, "请联系管理员");
		// }

		JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
		senderImpl.setDefaultEncoding("utf-8");
		senderImpl.setHost(current.getProperty(EmailParam.SEND_EMAIL_HOST.getSysPropName()));
		senderImpl.setUsername(current.getProperty(EmailParam.SEND_EMAIL_USER.getSysPropName()));
		senderImpl.setPassword(current.getProperty(EmailParam.SEND_EMAIL_PASSWORD.getSysPropName()));
		senderImpl.setJavaMailProperties(current);

		// SimpleMailMessage mail = new SimpleMailMessage();
		MimeMessage mail = senderImpl.createMimeMessage();
		MimeMessageHelper messageHelper;
		try {
			messageHelper = new MimeMessageHelper(mail, true);
			messageHelper.setFrom(current.getProperty(EmailParam.SEND_EMAIL_USER.getSysPropName()));
			messageHelper.setTo(emailAddress);
			messageHelper.setSubject(current.getProperty(EmailParam.SEND_EMAIL_SUBJECT.getSysPropName()));
			messageHelper.setText(MessageFormat.format(current.getProperty(EmailParam.SEND_EMAIL_MESSAGE.getSysPropName()), message), true);
			senderImpl.send(mail);
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
	}
}
